package com.simple.demo.io.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIO文件复制
 */
public class NIOCopy {

    public static void main(String[] args) {

        String source = "D:\\temp\\MotionProSetup_win64.zip";
        String target = "D:\\temp\\0602\\MotionProSetup_win64.zip";
        nioTransfer(source,target);
    }


    private static void nioTransfer(String sourcePath,String targetPath){

        try(FileInputStream fin = new FileInputStream(sourcePath);FileOutputStream fout = new FileOutputStream(targetPath)){

            FileChannel finChanel = fin.getChannel();
            FileChannel foutChanel = fout.getChannel();
            long len = finChanel.transferTo(0,finChanel.size(),foutChanel);
            finChanel.close();
            foutChanel.close();
            fout.close();
            fin.close();
            System.out.println("文件复制成功，文件总大小为：" + len);
        }catch (Exception ce){
            ce.printStackTrace();
        }finally {

        }

    }

    private static void niocopy(String sourcePath,String targetPath){
        //创建一个1024字节的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try(FileInputStream fin = new FileInputStream(sourcePath); FileOutputStream fout = new FileOutputStream(targetPath)){
            FileChannel finChanel = fin.getChannel();
            FileChannel foutChanel = fout.getChannel();
            int readLen =  finChanel.read(buffer);
            long size = 0;
            while(readLen > 0 ){
                buffer.flip();//读取模式切换为写模式
                foutChanel.write(buffer);
                buffer.clear();//清空进行下一次读取
                readLen = finChanel.read(buffer);
            }
            buffer.clear();
            foutChanel.close();
            finChanel.close();
            fout.close();
            fin.close();
            System.out.println("文件复制成功");

        }catch (Exception ce){
            ce.printStackTrace();
        }finally {

        }
    }

}
